package com.ruoyi.project.system.controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.aspectj.lang.annotation.Anonymous;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.project.system.domain.SmPay;
import com.ruoyi.project.system.domain.SmQuery;
import com.ruoyi.project.system.domain.vo.ProductQueryOrder;
import com.ruoyi.project.system.domain.vo.QueryVo;
import com.ruoyi.project.system.domain.vo.SysTax;
import com.ruoyi.project.system.mapper.SmPayMapper;
import com.ruoyi.project.system.mapper.SmQueryMapper;
import com.ruoyi.project.system.service.ISmQueryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.util.HashMap;
import java.util.List;

/**
 * 查询进件Controller
 */
@RestController
@RequestMapping("/system/query")
public class SmQueryController extends BaseController {
    @Autowired
    private ISmQueryService smQueryService;

    @Autowired
    private SmQueryMapper smQueryMapper;

    @Autowired
    private SmPayMapper smPayMapper;

    /**
     * 即时查询项目
     */
    @Anonymous
    @GetMapping("/data")
    public AjaxResult query(String name, @NotBlank(message = "没有单号") String orderNo) {
        SmPay smPay = smPayMapper.selectPayByOrderNo(orderNo);
        if (smPay == null) {
            return warn("不存在支付订单");
        } else if (!"SUCCESS".equals(smPay.getPayState())) {
            return warn("订单未支付");
        }
        SmQuery smQuery = smQueryMapper.selectSmQueryById(smPay.getOutId());
        if (smQuery != null && StringUtils.isNotEmpty(smQuery.getQueryInfo())) {
            smQuery.setUpdateTime(DateUtils.getNowDate());
        } else {
            AjaxResult query;
            if (smQuery.getProductId() == 1) {
                query = smQueryService.bigDataQueryPro(smQuery);
            } else if (smQuery.getProductId() == 2) {
                query = smQueryService.bigDataQuery(smQuery);
            } else if (smQuery.getProductId() == 4) {
                query = smQueryService.marryQuery(smQuery, orderNo);
            } else if (smQuery.getProductId() == 5) {
                query = smQueryService.judicialQuery(smQuery);
            } else {
                return error("没有此产品编号！");
            }
            for (String key : query.keySet()) {
                JSONObject value = (JSONObject) query.get(key);
                if (value.get("retdata") instanceof String) {
                    if (!"000000".equals(value.getString("retcode"))) {
                        return error("数据出错！");
                    }
                    String retdata = value.getString("retdata");
                    if ('[' == retdata.charAt(0)) {
                        value.replace("retdata", JSON.parseArray(retdata));
                    } else if ('{' == retdata.charAt(0)) {
                        value.replace("retdata", JSON.parseObject(retdata));
                    }
                    query.replace(key, value);
                }
            }
            String queryInfo = JSON.toJSONString(query);
            smQueryMapper.updateSmQuery(new SmQuery(smQuery.getId(), queryInfo));
            smQuery.setQueryInfo(queryInfo);
        }
        if (StringUtils.isNotEmpty(smQuery.getName())) {
            smQuery.setName("**" + smQuery.getName().substring(1));
        }
        if (StringUtils.isNotEmpty(smQuery.getCardNo())) {
            smQuery.setCardNo("******" + smQuery.getCardNo().substring(6));
        }
        if (StringUtils.isNotEmpty(smQuery.getTel())) {
            smQuery.setTel("*******" + smQuery.getTel().substring(7));
        }
        return success(smQuery);
    }

    /**
     * 新增企业查询
     */
    @Anonymous
    @PostMapping("/addPayTaxesQuery")
    public AjaxResult addPayTaxesQuery(@RequestBody SmQuery smQuery) {
        // 检查参数
        if (StringUtils.isEmpty(smQuery.getTel()) || smQuery.getUserId() == null) {
            return error("缺少参数！");
        }
        // 初级写入
        smQueryService.insertSmQuery(smQuery);
        // 发送请求
        JSONObject qyns = smQueryService.companyQuery(smQuery);
        if (!"000000".equals(qyns.getString("retcode"))) {
            return error(qyns.getString("retmsg"));
        }
        // 写入具体数据
        SysTax tax = new SysTax(smQuery.getId().intValue(), qyns.toJSONString());
        smQueryMapper.insertSysTax(tax);
        // 整理数据
        smQuery.setQueryInfo(tax.getId().toString());
        smQueryService.updateSmQuery(smQuery);

        smQuery.setQueryInfo(qyns.getJSONObject("retdata").toJSONString());
        return success(smQuery.getId());
    }

    /**
     * 获取纳税查询采集页面
     */
    @Anonymous
    @GetMapping("/getPayTaxesAuthUrl/{id}")
    public AjaxResult getPayTaxesAuthUrl(@PathVariable("id") @NotNull(message = "没有单号") Long id) {
        HashMap<String, String> tax = smQueryMapper.selectSysTaxByQueryId(id);
        if (tax == null || tax.isEmpty()) {
            return error("不存在的订单");
        }
        return success(tax);
    }

    /**
     * 获取企业纳税收集结果
     */
    @Anonymous
    @GetMapping("/getPayTaxes/{id}")
    public AjaxResult getPayTaxes(@PathVariable("id") @NotNull(message = "没有单号") Long id) {
        HashMap<String, String> taxMap = smQueryMapper.selectSysTaxByQueryId(id);
        JSONObject taxAuthUrl = JSON.parseObject(taxMap.get("taxAuthUrl"));
        String taskId = taxAuthUrl.getJSONObject("retdata").getString("taskId");
        String responseStr = HttpUtils.sendGet("http://175.178.170.139:8089/jiekou/qtrs?taskId=" + taskId);
        smQueryMapper.updateQueryTaxReportStatusOfTax(id, responseStr);
        return success(responseStr);
    }

    /**
     * 查询企业纳税
     */
    @Anonymous
    @GetMapping("/getPayTaxesData")
    public AjaxResult getPayTaxesData(String name, @NotBlank(message = "没有单号！") String orderNo) {
        SmPay smPay = smPayMapper.selectPayByOrderNo(orderNo);
        if (smPay == null) {
            return error("不存在的支付订单");
        } else if (!"SUCCESS".equals(smPay.getPayState())) {
            return error("订单未支付");
        }
        Long id = smPay.getOutId().longValue();
        HashMap<String, String> taxMap = smQueryMapper.selectSysTaxByQueryId(id);
        if (taxMap.isEmpty() || StringUtils.isEmpty(taxMap.get("queryTaxReport"))) {
            String requestSn = JSON.parseObject(taxMap.get("taxAuthUrl")).getString("request_sn");
            String returnStr = HttpUtils.sendGet("http://175.178.170.139:8089/jiekou/comInfo?requestSn=" + requestSn);
            smQueryMapper.updateQueryTaxReportOfTax(id, returnStr);
            if (StringUtils.isNotEmpty(returnStr) && JSON.parseObject(returnStr).getInteger("code") != 200) {
                return error("数据异常");
            }
            return success(JSON.parseObject(returnStr));
        } else {
            return success(JSON.parseObject(taxMap.get("queryTaxReport")));
        }
    }

    /**
     * 查询查询进件列表
     */
    @GetMapping("/product")
    public TableDataInfo product(ProductQueryOrder pqo) {
        pqo.setUserId(SecurityUtils.getUserId());
        startPage();
        List<ProductQueryOrder> list = smQueryMapper.productQueryOrders(pqo); // MGZ TODO 2025/4/14:产品查询记录
        return getDataTable(list);
    }

    /**
     * 新增查询进件
     */
    @Anonymous
    @PostMapping("/add")
    public AjaxResult add(@RequestBody SmQuery smQuery) {
        smQueryService.insertSmQuery(smQuery);
        return success(smQuery.getId());
    }

    /**
     * 查询查询进件列表
     */
    @PreAuthorize("@ss.hasPermi('system:query:list')")
    @GetMapping("/list")
    public TableDataInfo list(QueryVo queryVo) {
        startPage();
        List<QueryVo> list = smQueryService.selectSmQueryList(queryVo);
        return getDataTable(list);
    }

    /**
     * 获取查询进件详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:query:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Integer id) {
        return success(smQueryService.selectSmQueryById(id));
    }

    /**
     * 修改查询进件
     */
    @PreAuthorize("@ss.hasPermi('system:query:edit')")
    @Log(title = "查询进件", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SmQuery smQuery) {
        return toAjax(smQueryService.updateSmQuery(smQuery));
    }

    /**
     * 删除查询进件
     */
    @PreAuthorize("@ss.hasPermi('system:query:remove')")
    @Log(title = "查询进件", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Integer[] ids) {
        return toAjax(smQueryService.deleteSmQueryByIds(ids));
    }
}
